package top.lyc829.mymusic.model.repository

import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import top.lyc829.mymusic.model.bean.LoginParam
import top.lyc829.mymusic.model.http.AppException
import top.lyc829.mymusic.model.http.MyNetwork
import top.lyc829.mymusic.util.Const
import java.lang.RuntimeException

/**
 * @Author lyc
 * @create 2021-07-14 22:32
 */
class AuthRepository private constructor(private val network : MyNetwork) {


    suspend fun login(phone: String, password: String) = withContext(Dispatchers.IO) {
        val loginResult = network.login(LoginParam(phone, password))
        if (loginResult.code != Const.SUCCESS) {
            throw AppException(loginResult.code, loginResult.msg?:"登录失败")
        }
        MMKV.defaultMMKV().encode(Const.TOKEN, loginResult.token)
        loginResult
    }


    companion object {
        private var instance: AuthRepository? = null
        fun getInstance(network: MyNetwork): AuthRepository {
            if (instance == null) {
                synchronized(AuthRepository::class.java) {
                    if (instance == null) {
                        instance = AuthRepository(network)
                    }
                }
            }
            return instance!!
        }
    }

}